package com.cuit.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cuit.mapper.UsersMapper;
import com.cuit.params.UserLogin;
import com.cuit.pojo.Users;
import com.cuit.service.LoginService;
import com.cuit.service.MenuListService;
import com.cuit.service.ThreadMethod;
import com.cuit.utils.*;
import com.cuit.vo.MenuListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ThreadMethod threadMethod;

    @Autowired
    private MenuListService menuListService;

    @Override
    public Result login(UserLogin userLogin, HttpServletRequest request) {
//        if (HandlePasswordUtil.isWeekPassword(userLogin.getPassword())) {
//            return Result.fail(10002, "密码太简单，请重新设置");
//        }

        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getLoginName, userLogin.getUsername());
        Users users = usersMapper.selectOne(queryWrapper);
        if (users != null) {
            String password = users.getPassword();
            if (password.equals(DigestUtils.md5DigestAsHex(userLogin.getPassword().getBytes()))) {
                Map<String, String> map = new HashMap<>();
                map.put("users", JSON.toJSONString(users));
                String toKen = JWTUtils.getToKen(map);
                redisUtils.set(toKen, JSON.toJSONString(users));
                // 需要更新最后登录时间，最后登录ip 放在线程池中进行更新
                String ipAddr = IpUtils.getIpAddr(request);
                threadMethod.updateLoginIPAndTime(usersMapper, ipAddr, users);
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("users", users);
                resultMap.put("token", toKen);
                // 获得菜单
                List<MenuListVo> menuListUser = menuListService.getMenuListUser(users.getRoleId());
                resultMap.put("menuList",menuListUser);
                return Result.success(resultMap);
            } else {
                return Result.fail(406, "用户名或者密码错误");
            }
        } else {
            return Result.fail(406, "用户名或者密码错误");
        }
    }

//    private void getUserMenu(Integer roleID) {
//
//    }
}
